const { Sequelize } = require('sequelize');
// 注意：这里需要模拟appInfo参数来获取配置
const configFn = require('./config/config.default.js');
const appConfig = configFn({ name: 'lingxi-system' });

// 创建数据库连接
const sequelize = new Sequelize(appConfig.sequelize.database, appConfig.sequelize.username, appConfig.sequelize.password, {
  host: appConfig.sequelize.host,
  port: appConfig.sequelize.port,
  dialect: appConfig.sequelize.dialect,
  timezone: appConfig.sequelize.timezone,
  define: appConfig.sequelize.define,
  logging: false, // 关闭SQL日志
});

async function querySalesData() {
  try {
    // 测试数据库连接
    await sequelize.authenticate();
    console.log('数据库连接成功');
    
    // 查询销售订单数据
    console.log('\n=== 销售订单数据 ===');
    const orders = await sequelize.query('SELECT * FROM sales_orders LIMIT 5', { type: sequelize.QueryTypes.SELECT });
    console.log('订单数量:', orders.length);
    orders.forEach((order, index) => {
      console.log(`订单 ${index + 1}:`, JSON.stringify(order, null, 2));
    });
    
    // 查询销售订单项数据
    console.log('\n=== 销售订单项数据 ===');
    const orderItems = await sequelize.query('SELECT * FROM sales_order_items LIMIT 10', { type: sequelize.QueryTypes.SELECT });
    console.log('订单项数量:', orderItems.length);
    orderItems.forEach((item, index) => {
      console.log(`订单项 ${index + 1}:`, JSON.stringify(item, null, 2));
    });
    
    // 查询最新的插件数据批次
    console.log('\n=== 最新插件数据批次 ===');
    const batches = await sequelize.query('SELECT * FROM plugin_data_batches ORDER BY created_at DESC LIMIT 5', { type: sequelize.QueryTypes.SELECT });
    console.log('批次数量:', batches.length);
    batches.forEach((batch, index) => {
      console.log(`批次 ${index + 1}:`, JSON.stringify(batch, null, 2));
    });
    
    // 先查看plugin_data_items表结构
    console.log('\n=== plugin_data_items表结构 ===');
    try {
      const tableInfo = await sequelize.getQueryInterface().describeTable('plugin_data_items');
      console.log('表字段:', JSON.stringify(tableInfo, null, 2));
    } catch (error) {
      console.log('获取表结构失败:', error.message);
    }
    
    // 查询最新的插件数据项 (先不加WHERE条件)
    console.log('\n=== 最新插件数据项 ===');
    const items = await sequelize.query('SELECT * FROM plugin_data_items ORDER BY created_at DESC LIMIT 5', { type: sequelize.QueryTypes.SELECT });
    console.log('数据项数量:', items.length);
    items.forEach((item, index) => {
      console.log(`数据项 ${index + 1}:`, JSON.stringify(item, null, 2));
    });
    
  } catch (error) {
    console.error('查询数据时出错:', error);
  } finally {
    await sequelize.close();
  }
}

querySalesData();